const router = require('koa-router')()
const {
	login,
	addUser,
	queryName,
	getUserInfo
} = require('../db/function/userDB.js')
const {
	addToken
} = require('../utils/token.js')
const config = require('../config/index.js')
const md5 = require('md5')

router.prefix('/user')

// 登录接口  查询存不存在该账号
router.post('/login', async (ctx, next) => {
	console.log('=============');
	console.log(ctx.request.body);
	// ctx.body = JSON.stringify(ctx.request.body);
	let {
		username,
		password
	} = ctx.request.body;
	console.log('pwd',password);
	if (username == '' || password == '') {
		ctx.fail('请输入账号密码。')
		return false
	}
	if (config.md5) {
		password = md5(password)
	}
	console.log(password);
	let res = await login(username, password)
	if (res.length == 1) {
		// 生产token
		let token = addToken({
			user: username,
			id: res[0].id
		})
		const r = {
			token,
			info: res[0]
		}
		// 登录成功
		ctx.succ(r)
		return false
	} else {
		console.log('err');
		ctx.fail('账号或密码错误。')
		return false
	}
})

// 添加用户  注册用户
router.post('/createUser', async (ctx, next) => {
	console.log('postsdduer');
	let {
		username,
		password,
		name,
		phone,
		email,
		userimg
	} = ctx.request.body;
	if (username &&
		password &&
		name &&
		phone &&
		email) {
		// 查询存在相同username
		let isName = await queryName(username)
		console.log(isName.length);
		if (isName.length != 0) {
			ctx.fail('用户名已被占用')
			return false
		}
		if (config.md5) {
			password = md5(password)
		}
		let res = await addUser(username, password, name, phone, email, userimg)
		if (res.affectedRows == 1) {
			ctx.succ('添加成功')
			return false
		}
	} else {
		console.log('请填写必填信息');
		ctx.fail('请填写必填信息。')
		return false
	}
})

router.post('/userInfo', async (ctx, next) => {
	console.log('路由userInfo开始');
	if (ctx.state) {
		const tokenUser = ctx.state.user.user
		let res = await getUserInfo(tokenUser)
		console.log('sql查询结果', res);
		console.log('stutas:', ctx.state);
		if (res.length == 1) {
			const r = res[0]
			// 登录成功
			ctx.succ(r)
			return false
		} else {
			console.log('err');
			ctx.fail('账号或密码错误。')
			return false
		}
	} else {
		ctx.fail('token失效')
	}

})



module.exports = router
